﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using XbsWebAPI.EntityFrameworkCore;
using XbsWebAPI.EntityFrameworkCore.Entities.FeedBack;

namespace XbsWebAPI.Core.Repositories.Feedback
{
    public class FeedBackRepository : IFeedBackRepository
    {
        private readonly DataContext _dataContext;

        public FeedBackRepository(DataContext dataContext)
        {
            _dataContext = dataContext;
        }

        public IQueryable<FeedBack> AsQueryable()
        {
            return _dataContext.FeedBacks.AsQueryable();
        }

        public FeedBack Create(FeedBack entity)
        {
            var feedback = new FeedBack();

            var GuestModel = _dataContext.Guests.FirstOrDefault(a => a.Id == entity.GuestId);
            if (GuestModel == null)
                return null;
            feedback.Id = Guid.NewGuid();
            feedback.GuestId = GuestModel.Id;
            feedback.GuestName = GuestModel.Name;
            feedback.GuestPhone = GuestModel.PhoneNumber;
            feedback.CreationDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            feedback.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            feedback.Content = entity.Content;
            _dataContext.FeedBacks.Add(feedback);
            int save = _dataContext.SaveChanges();
            if (save <= 0)
                return null;
            return entity;
        }

        public Task<FeedBack> CreateAsync(FeedBack entity)
        {
            return Task.FromResult(Create(entity));
        }

        public FeedBack Delete(Guid id)
        {
            //通过Id查询数据
            var entity = _dataContext.FeedBacks.FirstOrDefault(a => a.Id == id);
            if (entity == null)
                throw new Exception($"ID={id}意见反馈不存在");
            _dataContext.FeedBacks.Remove(entity);
            _dataContext.SaveChanges();
            return entity;
        }

        public Task<FeedBack> DeleteAsync(Guid id)
        {
            return Task.FromResult(Delete(id));
        }

        public IQueryable<FeedBack> Query(Expression<Func<FeedBack, bool>> filter)
        {
            throw new NotImplementedException();
        }

        public FeedBack QueryById(Guid id)
        {
            throw new NotImplementedException();
        }

        public FeedBack Update(FeedBack entity)
        {
            throw new NotImplementedException();
        }

        public Task<FeedBack> UpdateAsync(FeedBack entity)
        {
            throw new NotImplementedException();
        }
    }
}
